<?php
/**
 * IndexController - The default controller class
 *
 * @author
 * @version
 */
require_once 'Zend/Controller/Action.php';

class PayController extends App_Zend_Controller_Action_Shop
{

    public function init()
    {
		$this->view->styleName = 'product';
		parent::init();
    }
    
    public function testAction()
    {
    	$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
    	if (defined('SELL_VALIDATE')) {
	    	$id = $this->getRequest()->getParam('id', 0);
	    	$order = new COrder();
	        $orderArray = $order->getAllOrders(0, 0, 0, R_PRE . "orders.orderid = $id AND has_shutted='0' AND " . R_PRE . "orders.flid='1'");//orders.uid='" . $paramArray['uid'] . "' and 
	        $uid = isset($orderArray[0]['uid']) ? $orderArray[0]['uid'] : 0;
	        
	        $orderidArray = array();
	
	        foreach ($orderArray as $value)
	        {
	            $orderidArray[] = $value['orderid'];
	        }
	        
	        $paid_total = $this->getHelper('Order')->getTotal($orderidArray);
	        
            $buyModel = new CPyramidMemberBuy();
            $buyModel->edit(array('is_pay'=>1), $id);
            $detailModel = new CPyramidAccountDetail();
            if (defined('IS_SELF')) {
            	$self = 1;
            } else {
            	$self = 0;
            }
            $detailModel->add(array('facebook_id'=>$_COOKIE[COOKIE_PRE.'inv_facebook_id'], 'from_facebook_id'=>$_COOKIE[COOKIE_PRE.'my_facebook_id'],
            						'amount'=>$paid_total * SELL_BONUS, 'order_id'=>$id, 'is_self'=>$self, 'add_time'=>time()));
            
            $accountModel = new CPyramidMemberAccount();
            //自己和好友的分成
            //$accountModel->addAmount($paid_total * SELL_BONUS, $_COOKIE[COOKIE_PRE.'my_facebook_id']);
            $accountModel->addAmount($paid_total * SELL_BONUS, $_COOKIE[COOKIE_PRE.'inv_facebook_id']);
            
            setcookie(COOKIE_PRE.'inv_facebook_id', $inv, time() - 1, '/');
			setcookie(COOKIE_PRE.'my_facebook_id', $currentUserId, time() - 1, '/');
			$invModel = new CPyramidMemberInv();
			
			$invModel->del($uid);
        }
    }


    public function paypalAction()
    {
        $email = $this->_request->getParam('email');
        $id = intval($this->getRequest()->getParam('id'));
        $member = new CMember();
        $memberArray = $member->getUserDetails(array('uid' => $_COOKIE[COOKIE_PRE . 'uid']));

        $order = new COrder();
        $total = 0;
        $orderArray = $order->getAllOrders(0, 0, $_COOKIE[COOKIE_PRE . 'uid'], "orderid = $id and has_shutted='0' AND " . R_PRE . "orders.flid='1'");
		if (empty($orderArray)) {
			$this->view->showMsg('error');
			return;
		}
		$total = $orderArray[0]['money'];
		$order->editOrder($orderArray[0]['orderid'], array('payment' => 'paypal', 'email_paypal'=>$email));
        $acctualTotal = $total * PAYPAL_RATE;
        $total = round($total, 2);
        $acctualTotal = round($acctualTotal, 2);
		$this->view->assign('total', $total);
        $this->view->assign('acctualTotal', $acctualTotal);
        $this->view->coupon = $orderArray[0]['coupon'];        
        $this->view->assign('item_name', '#PDO' . $orderArray[0]['orderid']);
		$this->view->assign('uid', $_COOKIE[COOKIE_PRE . 'uid']);
		$this->updateAccount($acctualTotal, 'paypal');
		return;
		$data = array('cmd'=>'_xclick', 'business'=>PAYPAL_ACCOUNT, 'item_name'=>'G' . $orderArray[0]['orderid'],
					  'item_number'=>$orderArray[0]['orderid'], 'amount'=>$acctualTotal, 'no_shipping'=>1,
					  'no_note'=>1, 'currency_code'=>'USD', 'notify_url'=>MY_URL . "/pay-receive?uid=" . $_COOKIE[COOKIE_PRE . 'uid'] . '&id=' . $id,
					  'return'=>MY_URL, 'cancel_return'=>MY_URL . '/product-addcontact');
		
		$this->updateAccount($acctualTotal, 'paypal');
		
		$str = http_build_query($data);
		$this->_redirect('http://www.whymind.com/pay/redirect.php?pay=paypal&' . $str);
    }
	
	/**富汇通表单**/
	public function payinfoAction()
    {
    	$this->view->webSiteTitle = 'Pay your order and get your jerseys soon';
    	/**$id = intval($this->getRequest()->getParam('id'));
    	
    	$order = new COrder();
        $total = 0;
        $orderArray = $order->getAllOrders(0, 0, $_COOKIE[COOKIE_PRE . 'uid'], "orderid = $id and has_shutted='0' AND " . R_PRE . "orders.flid='1'");
		if (empty($orderArray)) {
			$this->view->showMsg('error');
			return;
		}
		$total = $orderArray[0]['money'];
        $acctualTotal = $total * CE_SSFKH;
        $total = round($total, 2);
        $acctualTotal = round($acctualTotal, 2);
        
		$orderContact=new COrderContact();
        if($orderArray[0]['contactid'])
        {
            $buyerContactArray=$orderContact->getContactByid($orderArray[0]['contactid']);
        }else
        {
            $buyerContactArray=$orderContact->getContactByUid($orderArray[0]['uid']);
        }
		preg_match('/\((.*)\)/Usi', $buyerContactArray[0]['en_flname'], $match);
		$this->view->email = $buyerContactArray[0]['email'];//邮箱
		$this->view->phone = $buyerContactArray[0]['phone'];//电话
		$this->view->zip = $buyerContactArray[0]['post_code'];//邮编
		$this->view->address = $buyerContactArray[0]['content'];//地址
		$this->view->city = $buyerContactArray[0]['city'];//城市
		$this->view->state = $buyerContactArray[0]['state'];//省或者州
		$this->view->country = empty($match) ? '' : $match[1];//国家
		$this->view->amount = $acctualTotal;
		$this->view->id = $id;
		$this->view->error = $this->getRequest()->getParam("error", '0');**/
		$this->getHelper('layout')->disableLayout();
		//$this->getHelper('viewRenderer')->setNoRender();
    }
    
	public function curlPost($url, $data)                                                       
	{    
	        $ssl = substr($url, 0, 8) == "https://" ? TRUE : FALSE;                        
	       //echo $ssl; 
            $wesite ="http://" . $_SERVER['HTTP_HOST'];		   
	        $ch = curl_init();
	        curl_setopt($ch, CURLOPT_URL ,$url);
    	    curl_setopt($ch, CURLOPT_POST,1);                                              
			curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);                                   
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data);                                   
			curl_setopt($ch, CURLOPT_REFERER,$wesite);
	    if ($ssl){
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);                                 
	    	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	    }
	    $data = curl_exec($ch);
	    curl_close($ch);
		
	    return $data;                                                                  
	}
	
	/**富汇通**/
    public function ssfkh2Action()
    {
		//$this->getHelper('layout')->disableLayout();
		//$this->getHelper('viewRenderer')->setNoRender();
       
        $this->view->webSiteTitle = 'Pay your order and get your jerseys soon';
       
        session_start();
        $id = intval($this->getRequest()->getParam('id'));
        $bAddress = $_SESSION['Address'];
        $bCity = $_SESSION['City'];
        $bState = $_SESSION['State'];
        $bZip = $_SESSION['Zip'];
        $bCountry = $_SESSION['Country'];
        $bEmail = $_SESSION['Email'];
        $bPhone = $_SESSION['Phone'];
        
        $cardNo = $_SESSION['cardNo'];
        $cvv2 = $_SESSION['cvv2'];
        $cardExpireMonth = $_SESSION['cardExpireMonth'];
        $cardExpireYear = $_SESSION['cardExpireYear'];
        $IssuingBank = $_SESSION['IssuingBank'];
        $firstName = $_SESSION['firstName'];
        $lastName = $_SESSION['lastName'];
        
        if (empty($cardNo) || empty($cvv2) || empty($cardExpireMonth) || empty($cardExpireYear) || empty($IssuingBank) || empty($firstName) || empty($lastName) || 
        	empty($bAddress) || empty($bCity) ||  empty($bState) || empty($bZip) || empty($bCountry) || empty($bEmail) || empty($bPhone)) {
        	$this->_redirect("/pay-payinfo?id=" . $id . "&error=1");
        }

		$order = new COrder();
        $total = 0;
        $orderArray = $order->getAllOrders(0, 0, $_COOKIE[COOKIE_PRE . 'uid'], "orderid = $id and has_shutted='0' AND " . R_PRE . "orders.flid='1'");
		if (empty($orderArray)) {
			$this->view->showMsg('error');
			return;
		}
		$total = $orderArray[0]['money'];
        $acctualTotal = $total * CE_SSFKH;
        $total = round($total, 2);
        $acctualTotal = round($acctualTotal, 2);
    	
		$order->editOrder($orderArray[0]['orderid'], array('payment' => 'Credit Card'));
        $_COOKIE[COOKIE_PRE . 'integral'] = (int) ($acctualTotal / INTEGRALDH);
        $this->updateAccount($acctualTotal, 'Credit Card F');
        
		$orderContact=new COrderContact();
        if($orderArray[0]['contactid'])
        {
            $buyerContactArray=$orderContact->getContactByid($orderArray[0]['contactid']);
        }else
        {
            $buyerContactArray=$orderContact->getContactByUid($orderArray[0]['uid']);
        }
		preg_match('/\((.*)\)/Usi', $buyerContactArray[0]['en_flname'], $match);
        $data = array(
        	'MD5key'	=>	'123456',//MD5私钥
        	'MerNo'		=>	'1256',//商户号
        	'BillNo'	=>	$id,//[必填]订单号(商户自己产生：要求不重复)
        	'Currency'	=>	'15',//[必填]交易币种1:代表美金2:欧元4:英镑
        	'GoodsName' =>'Jerseys',
        	'CurrencyCode'	=>	'USD',
        	'Amount'	=>	$acctualTotal,//[必填]订单金额
        	'Language'	=>	'2',//[必填]语言2:代表英文；1：代表中文
        	'ReturnURL'	=>	MY_URL."/pay-ssfkhreceive1",//[必填]返回数据给商户的地址(商户自己填写):::注意请在测试前将该地址告诉我方人员;否则测试通不过
			'Remark'	=>	MY_URL,//[选填]填该网站的域名,方便以后维护和升级。
			'email'		=>	$buyerContactArray[0]['email'],//邮箱
			'phone'		=>	$buyerContactArray[0]['phone'],//电话
			'zip'	=>	$buyerContactArray[0]['post_code'],//邮编
			'shipAddress'	=>	$buyerContactArray[0]['content'],//地址
			'shipCity'		=>	$buyerContactArray[0]['city'],//城市
			'shipState'		=>	$buyerContactArray[0]['state'],//省或者州
			'shipCountry'	=>	empty($match) ? 'cn' : $match[1],//国家
        );
        $md5src = $data['MerNo'].$data['BillNo'].$data['Currency'] . $data['CurrencyCode'] .$data['Amount'].$data['Language'].$data['ReturnURL'].$data['MD5key'];//校验源字符串
		unset($data['MD5key']);
        $data['MD5info'] = strtoupper(md5($md5src));//MD5检验结果
        
        $MerNo = "1256";
	    $MD5key = "123456";			    			
		$BillNo = $id;
		$CurrencyCode = "USD";              
	    $Amount = $acctualTotal;
	    $Freight = $orderArray[0]['yunfeiprice'];
		$Fee="0";
		  // 账单信息
		  // 持卡人姓
		  $BFirstName= $firstName;
		  // 持卡人名
		  $BLastName= $lastName;
		  // 持卡人详细地址
		  $BillAddress = empty($bAddress) ? $buyerContactArray[0]['content'] : $bAddress;
		  // 持卡人城市
		  $BillCity = empty($bCity) ? $buyerContactArray[0]['city'] : $bCity;
		  // 持卡人省份
	      $BillState= empty($bState) ? $buyerContactArray[0]['state'] : $bState;
		  // 持卡人国家
		  $BillCountry = $bCountry;
		  // 持卡人邮编
	      $BillZip = empty($bZip) ? $buyerContactArray[0]['post_code'] : $bZip;
		  // 持卡人邮箱
	      $Email= empty($bEmail) ? $buyerContactArray[0]['email'] : $bEmail;
		  // 持卡人电话
	      $Phone= empty($bPhone) ? $buyerContactArray[0]['phone'] : $bPhone;
		  
		  // 收货信息
		  // 收货人姓
		  $SFirstName= $buyerContactArray[0]['name'];
		  // 收货人名
		  $SLastName= $buyerContactArray[0]['name'];
		  // 收货人详细地址
		  $ShipAddress=  $buyerContactArray[0]['content'];
		  // 收货人城市
		  $ShipCity= $buyerContactArray[0]['city'];
		  // 收货人省份
		  $ShipState= $buyerContactArray[0]['state'];
		  // 收货人国家
		  $ShipCountry= empty($match) ? $bCountry : $match[1];
		  // 收货人邮编
		  $ShipZip= $buyerContactArray[0]['post_code'];
	      $ShopName = "fancycheapjersey";
	      //通道参数，非语言
	      $Language = '2';	        
		  //支付页面语言
	      $LangCode = "EN" ;   
		  //通道参数
		  $Currency = '15';	    
		  //返回地址
		  $ReturnURL = MY_URL."/pay-ssfkhreceive1"; 	
	      // 备注
	      $Remark = ''; 
		  //校验源字符串
	      $md5src  = $MerNo.$BillNo.$Freight.$Amount.$Fee.$CurrencyCode.$ReturnURL.$Email.$MD5key;
		  //MD5检验结果
	      $MD5info = strtoupper(md5($md5src));
          $baseStr='<?xml version="1.0" encoding="UTF-8" ?><Order>';
	      $baseStr =$baseStr."<MerNo>".$MerNo ."</MerNo>";
		  $baseStr =$baseStr."<ShopName>".$ShopName."</ShopName>"; 
	      $baseStr =$baseStr."<BillNo>".$BillNo ."</BillNo>";
		  $baseStr =$baseStr."<GoodsList></GoodsList>";
	      $baseStr =$baseStr."<Amount>".$Amount ."</Amount>";
	      $baseStr =$baseStr."<Freight>".$Freight ."</Freight>";
		  $baseStr =$baseStr."<Fee>".$Fee."</Fee>";
	      $baseStr =$baseStr."<CurrencyCode>".$CurrencyCode ."</CurrencyCode>";
	      $baseStr =$baseStr."<BFirstName>".$BFirstName ."</BFirstName>"; 
	      $baseStr =$baseStr."<BLastName>".$BLastName ."</BLastName>";
		  $baseStr =$baseStr."<BillAddress>".$BillAddress ."</BillAddress>";
	      $baseStr =$baseStr."<BillCity>".$BillCity ."</BillCity>"; 
	      $baseStr =$baseStr."<BillState>".$BillState ."</BillState>";
	      $baseStr =$baseStr."<BillCountry>".$BillCountry ."</BillCountry>"; 
	      $baseStr =$baseStr."<BillZip>".$BillZip ."</BillZip>";
	      $baseStr =$baseStr."<Phone>".$Phone ."</Phone>";
	      $baseStr =$baseStr."<Email>".$Email ."</Email>";
	      $baseStr =$baseStr."<SFirstName>".$SFirstName ."</SFirstName>";  
	      $baseStr =$baseStr."<SLastName>".$SLastName ."</SLastName>"; 
		  $baseStr =$baseStr."<ShipAddress>".$ShipAddress ."</ShipAddress>"; 
		  $baseStr =$baseStr."<ShipCity>".$ShipCity ."</ShipCity>"; 
		  $baseStr =$baseStr."<ShipState>".$ShipState ."</ShipState>"; 
	      $baseStr =$baseStr."<ShipCountry>".$ShipCountry ."</ShipCountry>";
	      $baseStr =$baseStr."<ShipZip>".$ShipZip ."</ShipZip>"; 
	      $baseStr =$baseStr."<Language>".$Language ."</Language>"; 
	      $baseStr =$baseStr."<LangCode>".$LangCode ."</LangCode>"; 
	      $baseStr =$baseStr."<Currency>".$Currency ."</Currency>"; 
	      $baseStr =$baseStr."<ReturnURL>".$ReturnURL ."</ReturnURL>"; 
		  $baseStr =$baseStr."<Remark>".$Remark."</Remark>"; 
	      $baseStr =$baseStr."<MD5info>".$MD5info ."</MD5info>";  
	      $baseStr =$baseStr."<IssuingBank>".$IssuingBank."</IssuingBank>";
	      $baseStr =$baseStr."<CardNo>".$cardNo."</CardNo>";
		  $baseStr =$baseStr."<CVV>".$cvv2."</CVV>";
		  $baseStr =$baseStr."<ExpireYear>".$cardExpireYear."</ExpireYear>";
		  $baseStr =$baseStr."<ExpireMonth>".$cardExpireMonth."</ExpireMonth>";
		  $baseStr =$baseStr."<AcceptLanguage>".$_SERVER['HTTP_ACCEPT_LANGUAGE']."</AcceptLanguage>";
		  $baseStr =$baseStr."<UserAgent>".$_SERVER['HTTP_USER_AGENT']."</UserAgent>";
		  $baseStr =$baseStr."<Ipaddress>".$_SERVER['REMOTE_ADDR']."</Ipaddress></Order>";    
		  $TradeInfo = base64_encode(urlencode($baseStr)); 
		  
		  $returnData = $this->curlPost("https://ssl.rhythmbillpay.com/payment/DirPaymentProcess", "TradeInfo=".$TradeInfo);
		  $Decrydata=base64_decode($returnData);
		  
    	  $splitdata=array();
		  $edata=explode('&',$Decrydata);
		  foreach($edata as $key=>$value){		    
			$splitdata[$key]= explode('=',$value);
		  }
		  
		  //交易流水号
		  $TradeNo=$splitdata[0][1];
		  //订单号
		  $BillNo = $splitdata[1][1];
		  //通道参数
		  $Currency = $splitdata[8][1];
		  //金额
		  $Amount = $splitdata[9][1];
		  //支付状态
		  $Succeed = $splitdata[2][1];
		  //支付结果
		  $Result = $splitdata[3][1];
		  //取得的MD5校验信息
		  $MD5info = $splitdata[4][1]; 
		  //备注
		  $Remark = $_POST["Remark"];	
		  //MD5私钥
		  $MD5key = '123456';
		  //校验源字符串
		  $md5src = $BillNo.$Currency.$Amount.$Succeed.$MD5key;
		  //MD5检验结果
		  $md5sign = strtoupper(md5($md5src));
		  
		  $orderidArray[] = $id;
		  $uid = $_COOKIE[COOKIE_PRE . "uid"];
		  if(($Succeed=='0')) {
			$config=new CConfigpayemail();
        	$array=$config->getAllConfigpayemail();
	        $configArray=array();
	        foreach ($array as $value) {
	            $configArray[$value['name']]=$value['data'];
	        }
			$orderContact=new COrderContact();
	        $buyerContactArray=$orderContact->getContactByid($orderArray[0]['contactid']);
	        $to = $buyerContactArray[0]['email'];
	        $subject = str_replace("{#orderid}",$id, 'fancycheapjersey payment failure notice for order No.{#orderid}');
	        $message = "Dear $buyerContactArray[0]['name'],<br>
						We are sorry to inform that your payment for order #400 is failed due to following reason:<br>
						* payment declined by bank<br>
						You may use other credit card or other payment method to complete this payment. Sorry for the inconvenience caused. If there is any problem, please let us know throungh Facebook post. We will get back to you as soon as possible.<br> 
						Regards,<br>
						fancycheapjersey"	;	
	        $message = str_replace("\r\n","<br>",$message);
	        $from = $configArray['EMAIL_BOX'];
	        $headers = "MIME-Version: 1.0" . "\r\n";
	        $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
	        $headers .= "From: $from";
	        mail($to,$subject,$message,$headers);
	  	  }else if(1 && ($Succeed=='1')){
		  	$allInfoArray = array();

            $paid_total = $this->getHelper('Order')->getTotal($orderidArray);
            $paid_total = $paid_total * CE_SSFKH;
            
                       	
            $this->updateIntegral($paid_total, $uid); //更新积分
            $score = new CScore();
            if ($score->orderScore('statu')) {
            	$scorePayStatu = 1;
            	$orderScoreStatu = 1;
            } else {
            	$scorePayStatu = 0;
            	$orderScoreStatu = 0;
            }
            $member = new CMember();   
            $useScore = $score->dollar2score($orderArray[0]['coupon']);    	
            //$member->updateIntegral($useScore, $uid);			    
            $order->editOrderArray($orderidArray, array('score_pay_statu'=>$scorePayStatu,'order_score_statu'=>$orderScoreStatu, 'flid' => 2, 'payment' => 'Credit Card', 'discount' => CE_SSFKH, 'pay_time' => time()));
            $account = new CAccount();
            $sign = $orderidArray[count($orderidArray) - 1];
            $accountArray = $account->getAccountDetails(array('sign' => $sign));
            if (count($accountArray) == 0)
            {
                // 财务 
                $accountData = array(
                    'should_paid' => $acctualTotal,
                    'has_paid' => $Amount,
                    'flid' => 1,
                    'state' => 1,
                    'orderid_string' => serialize($orderidArray),
                    'from_uid' => $uid,
                    'to_uid' => 0,
                    'add_time' => time(),
                    'payment' => 'Credit Card',
                    'remark' => ''
                );

                $account->createAccount($accountData);
                // 财务 
            } else {
                $accountData = array(
                    'should_paid' => $acctualTotal,
                    'has_paid' => $Amount,
                    'flid' => 1,
                    'state' => 1,
                    'orderid_string' => serialize($orderidArray),
                    'from_uid' => $uid,
                    'to_uid' => 0,
                    'add_time' => time(),
                    'payment' => 'Credit Card',
                    'remark' => ''
                );

                $account->editAccount($accountArray[0]['accountid'], $accountData);
            }

            $cart = new CCart();
	    	$db = $cart->getAdapter();
	    	$member = new CMember();
	    	if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer'){
	    		$where = $db->quoteInto('cart_session_id = ?', $_COOKIE[COOKIE_PRE . 'product_buy_session']);    
	    		setcookie(COOKIE_PRE.'product_buy_session', '', time()-3600, '/');
	    	} else {
	    		$where = $db->quoteInto('uid = ?', $_COOKIE[COOKIE_PRE . 'uid']);
	    	}	
	    	$cart->delete($where);

	    	//发送邮件
            $config=new CConfigpayemail();
        	$array=$config->getAllConfigpayemail();
	        $configArray=array();
	        foreach ($array as $value) {
	            $configArray[$value['name']]=$value['data'];
	        }
        	
        	$orderContact=new COrderContact();
	        $buyerContactArray=$orderContact->getContactByid($orderArray[0]['contactid']);
	        $to = $buyerContactArray[0]['email'];
	        $subject = $configArray['EMAIL_TITLE'];
	        $message = str_replace("{#orderid}",$id, $configArray['EMAIL_BODY']);	
	
	        $message = str_replace("\r\n","<br>",$message);
	        $from = $configArray['EMAIL_BOX'];
	        $headers = "MIME-Version: 1.0" . "\r\n";
	        $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
	        $headers .= "From: $from";
	        mail($to,$subject,$message,$headers);
	        
	        $flashCommon = new CFlashcommon();
			$flashCommon->addItem($uid, 10);
			$flashItemLog = new CFlashitemorderlog();      
			$flashItemLog->insert(array('orderid'=>$id, 'buy_count'=>10, 'add_time'=>time()));
        	CStock::update($id); //更新库存
		  } else {
			  
		  }       
		
    	$confirmation = new CConfirmation();
        $data = array(
            'uid' => $uid,
            'orderid_string' => serialize($orderidArray),
            'confirm_string' => serialize($allInfoArray),
            'add_time' => time(),
            'is_valid' => 1 ? 1 : 0,
            'total' => "0" . $Amount,
            'paid_total' => $Amount,
        );

		$confirmation->createConfirmation($data);
		$this->view->md5sign = $md5sign;
		$this->view->MD5info = $MD5info;
		if (1){
        	$this->view->BillNo = $BillNo;
			$this->view->Currency = $Currency;
			$this->view->Amount = $Amount;
			$this->view->Succeed = $Succeed;
			$this->view->Result = $Result;
			//$this->view->currencyName = $currencyName;
			$this->view->md5src = $md5src;
			$this->view->orderid = $id;
		}
		if ($returnData) {
			$payStatu = new CPaystatu();
			$payStatu->add(array('orderid'=>$BillNo, 'statu'=>$Result . ' by custom', 'add_time'=>date('Y-m-d H:i:s', time())));
		}
    }
	
    /**富汇通**/
    public function ssfkh1Action()
    {
		//$this->getHelper('layout')->disableLayout();
		//$this->getHelper('viewRenderer')->setNoRender();
       
       $this->view->webSiteTitle = 'Pay your order and get your jerseys soon';
       
        $id = intval($this->getRequest()->getParam('id'));

		$order = new COrder();
        $total = 0;
        $orderArray = $order->getAllOrders(0, 0, $_COOKIE[COOKIE_PRE . 'uid'], "orderid = $id and has_shutted='0' AND " . R_PRE . "orders.flid='1'");
		if (empty($orderArray)) {
			$this->view->showMsg('error');
			return;
		}
		$total = $orderArray[0]['money'];
        $acctualTotal = $total * CE_SSFKH;
        $total = round($total, 2);
        $acctualTotal = round($acctualTotal, 2);
    	if ($acctualTotal > 1500) {
			echo "<script>alert('Sorry,$1500 dollars limited.');history.go(-1);</script>";
			return;
		}
		$order->editOrder($orderArray[0]['orderid'], array('payment' => 'Credit Card'));
        $_COOKIE[COOKIE_PRE . 'integral'] = (int) ($acctualTotal / INTEGRALDH);
        $this->updateAccount($acctualTotal, 'Credit Card F');
        
		$orderContact=new COrderContact();
        if($orderArray[0]['contactid'])
        {
            $buyerContactArray=$orderContact->getContactByid($orderArray[0]['contactid']);
        }else
        {
            $buyerContactArray=$orderContact->getContactByUid($orderArray[0]['uid']);
        }
		preg_match('/\((.*)\)/Usi', $buyerContactArray[0]['en_flname'], $match);
        $data = array(
        	'MD5key'	=>	'123456',//MD5私钥
        	'MerNo'		=>	'1256',//商户号
        	'BillNo'	=>	$id,//[必填]订单号(商户自己产生：要求不重复)
        	'Currency'	=>	'15',//[必填]交易币种1:代表美金2:欧元4:英镑
        	'GoodsName' =>'Jerseys',
        	'CurrencyCode'	=>	'USD',
        	'Amount'	=>	$acctualTotal,//[必填]订单金额
        	'Language'	=>	'2',//[必填]语言2:代表英文；1：代表中文
        	'ReturnURL'	=>	MY_URL."/pay-ssfkhreceive1",//[必填]返回数据给商户的地址(商户自己填写):::注意请在测试前将该地址告诉我方人员;否则测试通不过
			'Remark'	=>	MY_URL,//[选填]填该网站的域名,方便以后维护和升级。
			'email'		=>	$buyerContactArray[0]['email'],//邮箱
			'phone'		=>	$buyerContactArray[0]['phone'],//电话
			'zip'	=>	$buyerContactArray[0]['post_code'],//邮编
			'shipAddress'	=>	$buyerContactArray[0]['content'],//地址
			'shipCity'		=>	$buyerContactArray[0]['city'],//城市
			'shipState'		=>	$buyerContactArray[0]['state'],//省或者州
			'shipCountry'	=>	empty($match) ? 'cn' : $match[1],//国家
        );
        $md5src = $data['MerNo'].$data['BillNo'].$data['Currency'] . $data['CurrencyCode'] .$data['Amount'].$data['Language'].$data['ReturnURL'].$data['MD5key'];//校验源字符串
		unset($data['MD5key']);
        $data['MD5info'] = strtoupper(md5($md5src));//MD5检验结果
        
        $MerNo = "1256";
	    $MD5key = "123456";			    			
		$BillNo = $id;
		$CurrencyCode = "USD";              
	    $Amount = $acctualTotal;
	    $Freight = $orderArray[0]['yunfeiprice'];
		$Fee="0";
		  // 账单信息
		  // 持卡人姓
		  $BFirstName= '';
		  // 持卡人名
		  $BLastName= '';
		  // 持卡人详细地址
		  $BillAddress= $buyerContactArray[0]['content'];
		  // 持卡人城市
		  $BillCity=$buyerContactArray[0]['city'];
		  // 持卡人省份
	      $BillState= $buyerContactArray[0]['state'];
		  // 持卡人国家
		  $BillCountry= empty($match) ? '' : $match[1];
		  // 持卡人邮编
	      $BillZip=$buyerContactArray[0]['post_code'];
		  // 持卡人邮箱
	      $Email= $buyerContactArray[0]['email'];
		  // 持卡人电话
	      $Phone= $buyerContactArray[0]['phone'];
		  
		  // 收货信息
		  // 收货人姓
		  $SFirstName= $buyerContactArray[0]['name'];
		  // 收货人名
		  $SLastName= $buyerContactArray[0]['name'];
		  // 收货人详细地址
		  $ShipAddress=  $buyerContactArray[0]['content'];
		  // 收货人城市
		  $ShipCity= $buyerContactArray[0]['city'];
		  // 收货人省份
		  $ShipState= $buyerContactArray[0]['state'];
		  // 收货人国家
		  $ShipCountry= empty($match) ? '' : $match[1];
		  // 收货人邮编
		  $ShipZip= $buyerContactArray[0]['post_code'];
	      $ShopName = "fancycheapjersey";
	      //通道参数，非语言
	      $Language = '2';	        
		  //支付页面语言
	      $LangCode = "EN" ;   
		  //通道参数
		  $Currency = '15';	    
		  //返回地址
		  $ReturnURL = MY_URL."/pay-ssfkhreceive1"; 	
	      // 备注
	      $Remark = ''; 
		  //校验源字符串
	      $md5src  = $MerNo.$BillNo.$Freight.$Amount.$Fee.$CurrencyCode.$ReturnURL.$Email.$MD5key;
		  //MD5检验结果
	      $MD5info = strtoupper(md5($md5src));
          $baseStr='<?xml version="1.0" encoding="UTF-8" ?><Order>';
	      $baseStr =$baseStr."<MerNo>".$MerNo ."</MerNo>";
		  $baseStr =$baseStr."<ShopName>".$ShopName."</ShopName>"; 
	      $baseStr =$baseStr."<BillNo>".$BillNo ."</BillNo>";
		  $baseStr=$baseStr."<GoodsList></GoodsList>";
	      $baseStr =$baseStr."<Amount>".$Amount ."</Amount>";
	      $baseStr =$baseStr."<Freight>".$Freight ."</Freight>";
		  $baseStr =$baseStr."<Fee>".$Fee."</Fee>";
	      $baseStr =$baseStr."<CurrencyCode>".$CurrencyCode ."</CurrencyCode>";
	      $baseStr =$baseStr."<BFirstName>".$BFirstName ."</BFirstName>"; 
	      $baseStr =$baseStr."<BLastName>".$BLastName ."</BLastName>";
		  $baseStr =$baseStr."<BillAddress>".$BillAddress ."</BillAddress>";
	      $baseStr =$baseStr."<BillCity>".$BillCity ."</BillCity>"; 
	      $baseStr =$baseStr."<BillState>".$BillState ."</BillState>";
	      $baseStr =$baseStr."<BillCountry>".$BillCountry ."</BillCountry>"; 
	      $baseStr =$baseStr."<BillZip>".$BillZip ."</BillZip>";
	      $baseStr =$baseStr."<Phone>".$Phone ."</Phone>";
	      $baseStr =$baseStr."<Email>".$Email ."</Email>";
	      $baseStr =$baseStr."<SFirstName>".$SFirstName ."</SFirstName>";  
	      $baseStr =$baseStr."<SLastName>".$SLastName ."</SLastName>"; 
		  $baseStr =$baseStr."<ShipAddress>".$ShipAddress ."</ShipAddress>"; 
		  $baseStr =$baseStr."<ShipCity>".$ShipCity ."</ShipCity>"; 
		  $baseStr =$baseStr."<ShipState>".$ShipState ."</ShipState>"; 
	      $baseStr =$baseStr."<ShipCountry>".$ShipCountry ."</ShipCountry>";
	      $baseStr =$baseStr."<ShipZip>".$ShipZip ."</ShipZip>"; 
	      $baseStr =$baseStr."<Language>".$Language ."</Language>"; 
	      $baseStr =$baseStr."<LangCode>".$LangCode ."</LangCode>"; 
	      $baseStr =$baseStr."<Currency>".$Currency ."</Currency>"; 
	      $baseStr =$baseStr."<ReturnURL>".$ReturnURL ."</ReturnURL>"; 
		  $baseStr =$baseStr."<Remark>".$Remark."</Remark>"; 
	      $baseStr =$baseStr."<MD5info>".$MD5info ."</MD5info></Order>";      
		  $TradeInfo =base64_encode(urlencode($baseStr)); 
		
		  $this->view->url = "https://ssl.rhythmbillpay.com/payment/InterfaceMix";
		  $this->view->TradeInfo = $TradeInfo;
		  $this->view->BillNo = $BillNo;
		  $this->view->Amount = $Amount;
		  
		  //google  trace
		  $orderTrace = "_gaq.push(['_addTrans',
								    '$id',           // transaction ID - required
								    'fancycheapjersey',  // affiliation or store name
								    '$Amount',          // total - required
								    '0.00',           // tax
								    '0',              // shipping
								    '$ShipCity',       // city
								    '$ShipState',     // state or province
								    '$ShipCountry'             // country
								  ]);";
		  
		  $itemArray=unserialize(stripslashes($orderArray[0]['order_string']));
		  $tmp = '';
		  foreach($itemArray as $value) {
		  		$tmp .= " _gaq.push(['_addItem',
								    '$id',           // transaction ID - required
								    '".$value['itemid']."',           // SKU/code - required
								    '".$value['subject']."',        // product name
								    'Soccer',   // category or variation
								    '".$value['net_price']."',          // unit price - required
								    '".$value['amounts']."'               // quantity - required
								  ]);";
		  }
		  $orderTrace .= $tmp;					 
		  $orderTrace .= "_gaq.push(['_trackTrans']);";
		  $this->view->orderTrace = $orderTrace;
		//$this->_redirect(MY_URL.'/pay-visapayment?url='.base64_encode('https://payment.hooppay.com/payment/InterfaceMix?TradeInfo=' . $TradeInfo));
    }
    
	public function ssfkhAction()
    {
		$this->getHelper('layout')->disableLayout();
		$this->getHelper('viewRenderer')->setNoRender();
       
        $id = intval($this->getRequest()->getParam('id'));

		$order = new COrder();
        $total = 0;
        $orderArray = $order->getAllOrders(0, 0, $_COOKIE[COOKIE_PRE . 'uid'], "orderid = $id and has_shutted='0' AND " . R_PRE . "orders.flid='1'");
		if (empty($orderArray)) {
			$this->view->showMsg('error');
			return;
		}
		$total = $orderArray[0]['money'];
        $acctualTotal = $total * CE_SSFKH;
        $total = round($total, 2);
        $acctualTotal = round($acctualTotal, 2);
    	if ($acctualTotal > 1500) {
			echo "<script>alert('Sorry,$1500 dollars limited.');history.go(-1);</script>";
			return;
		}
		$order->editOrder($orderArray[0]['orderid'], array('payment' => 'Credit Card'));
        $_COOKIE[COOKIE_PRE . 'integral'] = (int) ($acctualTotal / INTEGRALDH);
        $this->updateAccount($acctualTotal, 'Credit Card');
        
		$orderContact=new COrderContact();
        if($orderArray[0]['contactid'])
        {
            $buyerContactArray=$orderContact->getContactByid($orderArray[0]['contactid']);
        }else
        {
            $buyerContactArray=$orderContact->getContactByUid($orderArray[0]['uid']);
        }
		
        $data = array(
        	'MD5key'	=>	'Zwj(u^qe',//MD5私钥
        	'MerNo'		=>	'10181',//商户号
        	'BillNo'	=>	$id,//[必填]订单号(商户自己产生：要求不重复)
        	'Currency'	=>	'1',//[必填]交易币种1:代表美金2:欧元4:英镑
        	'Amount'	=>	$acctualTotal,//[必填]订单金额
        	'Language'	=>	'2',//[必填]语言2:代表英文；1：代表中文
        	'ReturnURL'	=>	MY_URL."/pay-ssfkhreceive",//[必填]返回数据给商户的地址(商户自己填写):::注意请在测试前将该地址告诉我方人员;否则测试通不过
			'Remark'	=>	MY_URL,//[选填]填该网站的域名,方便以后维护和升级。
			'DeliveryFirstName'	=>	'',//姓
			'DeliveryLastName'	=>	'',//名
			'DeliveryEmail'		=>	$buyerContactArray[0]['email'],//邮箱
			'DeliveryPhone'		=>	$buyerContactArray[0]['phone'],//电话
			'DeliveryZipCode'	=>	$buyerContactArray[0]['post_code'],//邮编
			'DeliveryAddress'	=>	$buyerContactArray[0]['content'],//地址
			'DeliveryCity'		=>	$buyerContactArray[0]['city'],//城市
			'DeliveryState'		=>	$buyerContactArray[0]['state'],//省或者州
			'DeliveryCountry'	=>	$buyerContactArray[0]['en_flname'],//国家
        );
        $md5src = $data['MerNo'].$data['BillNo'].$data['Currency'].$data['Amount'].$data['Language'].$data['ReturnURL'].$data['MD5key'];//校验源字符串
		$data['MD5info'] = strtoupper(md5($md5src));//MD5检验结果
		$str = http_build_query($data);
		$this->_redirect(MY_URL.'/pay-visapayment?url='.base64_encode('https://security.immepay.com/sslpayment?' . $str));
    }
    
	public function yourspayAction()
    {
		$this->getHelper('layout')->disableLayout();
		$this->getHelper('viewRenderer')->setNoRender();
       
        $id = intval($this->getRequest()->getParam('id'));

		$order = new COrder();
        $total = 0;
        $orderArray = $order->getAllOrders(0, 0, $_COOKIE[COOKIE_PRE . 'uid'], "orderid = $id and has_shutted='0' AND " . R_PRE . "orders.flid='1'");
		if (empty($orderArray)) {
			$this->view->showMsg('error');
			return;
		}
		$total = $orderArray[0]['money'];
        $acctualTotal = $total * CE_SSFKH;
        $total = round($total, 2);
        $acctualTotal = round($acctualTotal, 2);
    	if ($acctualTotal > 1500) {
			echo "<script>alert('Sorry,$1500 dollars limited.');history.go(-1);</script>";
			return;
		}
		$order->editOrder($orderArray[0]['orderid'], array('payment' => 'Credit Card'));
        $_COOKIE[COOKIE_PRE . 'integral'] = (int) ($acctualTotal / INTEGRALDH);
        $this->updateAccount($acctualTotal, 'Credit Card');
        
		$orderContact=new COrderContact();
        if($orderArray[0]['contactid'])
        {
            $buyerContactArray=$orderContact->getContactByid($orderArray[0]['contactid']);
        }else
        {
            $buyerContactArray=$orderContact->getContactByUid($orderArray[0]['uid']);
        }
		
        

		$MerNo = "2994";                     /** <必填>--商户号. **/
		$BillNo = $id;		                 /** <必填>--订单号. 由网店系统产生,24小时内不能重复,可以是字母和数字的组合. **/
		$MD5key = "pIesLirt";	             /** <必填>--密钥. 可以在YourSpay商户后台查询和修改,为了支付安全,建议一段时间更换一次. **/
		$Amount = $acctualTotal;		     /** <必填>--订单总金额.包括运费在内. 必须只能为数字,并且大于0,最多为小数点两位. **/ 
		$Freight = $orderArray[0]['yunfeiprice'];	                 /** <必填>--运费. 必须只能为数字,最多为小数点两位,如果无运费,可以为设为0. **/
		$CurrencyCode = "USD";			     /** <必填>--币种. 美元:USD,英镑:GBP,欧元:EUR,加元:CAD,澳元:AUD,日元:JPY. **/		
		$BFirstName = "";       /** <可选>--持卡人姓. 如果网店只有一个全名,建议把全名对姓和名各赋值一份. **/
		$BLastName = "";         /** <可选>--持卡人名. 如果网店只有一个全名,建议把全名对姓和名各赋值一份. **/
		$Email = $buyerContactArray[0]['email'];             /** <必填>--持卡人邮箱.  用于支付成功或者失败,向客户发送支付成功/失败提示邮件. **/
		$Phone = $buyerContactArray[0]['phone'];			     /** <可选>--持卡人电话. **/
		$BillAddress = $buyerContactArray[0]['content'];        /** <可选>--详细地址. **/
		$BillCity = $buyerContactArray[0]['city'];		         /** <可选>--城市. **/
		$BillState = $buyerContactArray[0]['state'];            /** <可选>--省份/州. **/
		$BillCountry = "";                 /** <可选>--国家. 国家名称最好用大写,而且是国家简称. **/
		$BillZip = $buyerContactArray[0]['post_code'];				 /** <可选>--邮编. **/	
		/** 收货人信息 **/	
		$SFirstName = $buyerContactArray[0]['name'];       /** <必填>--收货人姓. 如果网店只有一个全名,建议把全名对姓和名各赋值一份. **/
		$SLastName = $buyerContactArray[0]['name'];         /** <必填>--收货人名. 如果网店只有一个全名,建议把全名对姓和名各赋值一份. **/
		$ShipAddress = $buyerContactArray[0]['content'];	     /** <必填>--详细地址. **/
		$ShipCity = $buyerContactArray[0]['city'];		         /** <必填>--城市. **/
		$ShipState	= $buyerContactArray[0]['state'];	         /** <可选>--省份/州. **/
		$ShipCountry = $buyerContactArray[0]['en_flname'];	     /** <必填>--国家. 国家名称最好用大写,而且是国家简称. **/
		$ShipZip = $buyerContactArray[0]['post_code'];                 /** <必填>--邮编. **/
		$ShipEmail="";          /** <可选>--邮箱. **/
		$ShipPhone="";               /** <可选>--电话. **/   
		
		/** 通道信息 **/
		$Language = "2";		             /** <必填>--通道参数,非语言,只能为固定值:2. **/
		$LangCode = "en";		             /** <可选>--支付页面语言. 英文:en,法语:fr,意大利语:it,德语:de,日语:ja,默认为英文(en). **/
		$Currency = "15";	                 /** <必填>--通道参数.非币种,只能为固定值:15. **/
		$ReturnURL	= MY_URL."/pay-yourspayreceive";	  /** <必填>--返回页面. 支付完成后,将返回到此页面,提示支 付的结果(成功/失败). **/
		$Remark = "";	 /** <可选>--备注. 网店中客户填写的备注. **/
		
		$itemArray=unserialize($orderArray[0]['order_string']);
		$GoodsListInfo = '';
		foreach ($GoodsListInfo as $v) {	
    		$GoodsListInfo = $GoodsListInfo ."<Goods><GoodsName>".$v['subject']."</GoodsName><Qty>".$v['amounts']."</Qty><Price>".$v['net_price']."</Price></Goods>";
		}
		$md5src = $MerNo.$BillNo.$Freight.$Amount.$CurrencyCode.$ReturnURL.$Email.$MD5key;    /** 参数组合, 顺序不能颠倒 **/
		$MD5info = strtoupper(md5($md5src));     /** 对参数组合字符串进行md5加密,并且转换为大写 **/
		
		/** 把参数用xml组合成字符串 **/
		$basexml = '<?xml version="1.0" encoding="UTF-8" ?><Order>';
		$basexml = $basexml."<MerNo>". $MerNo ."</MerNo>";
		$basexml = $basexml."<BillNo>". $BillNo ."</BillNo>";
		$basexml = $basexml."<GoodsList>" . $GoodsListInfo ."</GoodsList>";
		$basexml = $basexml."<Amount>". $Amount ."</Amount>";
		$basexml = $basexml."<Freight>". $Freight ."</Freight>";
		$basexml = $basexml."<CurrencyCode>". $CurrencyCode ."</CurrencyCode>";
		$basexml = $basexml."<BFirstName>". $BFirstName ."</BFirstName>";
		$basexml = $basexml."<BLastName>". $BLastName ."</BLastName>";
		$basexml = $basexml."<Email>". $Email ."</Email>";
		$basexml = $basexml."<Phone>". $Phone ."</Phone>";
		$basexml = $basexml."<BillAddress>". $BillAddress ."</BillAddress>";
		$basexml = $basexml."<BillCity>". $BillCity ."</BillCity>";
		$basexml = $basexml."<BillState>". $BillState ."</BillState>";
		$basexml = $basexml."<BillCountry>". $BillCountry ."</BillCountry>";
		$basexml = $basexml."<BillZip>". $BillZip ."</BillZip>";
		$basexml = $basexml."<SFirstName>". $SFirstName ."</SFirstName>";
		$basexml = $basexml."<SLastName>". $SLastName . "</SLastName>";
		$basexml = $basexml."<ShipAddress>". $ShipAddress ."</ShipAddress>";
		$basexml = $basexml."<ShipCity>". $ShipCity ."</ShipCity>";
		$basexml = $basexml."<ShipState>". $ShipState ."</ShipState>";
		$basexml = $basexml."<ShipCountry>". $ShipCountry ."</ShipCountry>";
		$basexml = $basexml."<ShipZip>". $ShipZip ."</ShipZip>";
		$basexml = $basexml."<ShipEmail>". $ShipEmail ."</ShipEmail>";
		$basexml = $basexml."<ShipPhone>". $ShipPhone ."</ShipPhone>";
		$basexml = $basexml."<Language>". $Language ."</Language>";
		$basexml = $basexml."<LangCode>". $LangCode ."</LangCode>";
		$basexml = $basexml."<Currency>". $Currency ."</Currency>";
		$basexml = $basexml."<ReturnURL>". $ReturnURL ."</ReturnURL>";
		$basexml = $basexml."<Remark>". $Remark ."</Remark>";
		$basexml = $basexml."<MD5info>". $MD5info ."</MD5info></Order>";	
		$TradeInfo = base64_encode(urlencode($basexml));
		//$this->_redirect('https://security.credit-pay.com/sslpayment/InterfaceMix?TradeInfo=' . $TradeInfo);
		$this->_redirect(MY_URL.'/pay-visapayment?url='.base64_encode('https://security.credit-pay.com/sslpayment/InterfaceMix?TradeInfo=' . $TradeInfo));
    }
    
    public function visapaymentAction(){
    	$member = new CMember(); 
    	if(!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer') {
            $this->_redirect(MY_URL.'/auth-login?preurl=/product-showitem');
            return;
        }
    	$paymenturl = $this->getRequest()->getParam('url');
    	$this->view->paymenturl = base64_decode($paymenturl);
    	$this->view->noLongBanner = 1;
    	$this->view->webSiteTitle = 'Pay your order and get your jerseys soon';
    }

    public function westAction()
    {
		 
       $this->view->webSiteTitle = 'Pay your order and get your jerseys soon';
       
        $id = intval($this->getRequest()->getParam('id'));

		$order = new COrder();
        $total = 0;
        $orderArray = $order->getAllOrders(0, 0, $_COOKIE[COOKIE_PRE . 'uid'], "orderid = $id and has_shutted='0' AND " . R_PRE . "orders.flid='1'");
		if (empty($orderArray)) {
			$this->view->showMsg('error');
			return;
		}
		$total = $orderArray[0]['money'];
        $acctualTotal = $total * CE_SSFKH;
        $total = round($total, 2);
        $acctualTotal = round($acctualTotal, 2);
        
        
        $this->view->total = $acctualTotal;
        $this->view->id = $id;
        $order->editOrder($id, array('payment' => 'West Union'));
        return;
        $my_coupon = $this->_request->getParam('my_coupon');

        $my_coupon = $my_coupon == '' ? 0 : $my_coupon;

        $member = new CMember();

        $memberArray = $member->getUserDetails(array('uid' => $_COOKIE[COOKIE_PRE . 'uid']));

        if ($memberArray[0]['my_coupon'] < $my_coupon)
        {

            $this->_helper->viewRenderer->setNoRender();

            $this->view->showMsg("Not enough coupons!");
        } else
        {

            $item_name = $this->_request->getParam('item_name');

            $order = new COrder();

            $total = 0;

            $orderArray = $order->getAllOrders(0, 0, $_COOKIE[COOKIE_PRE . 'uid'], "has_shutted='0' AND " . R_PRE . "orders.flid='1'");

            foreach ($orderArray as $value)
            {

                $total+=$value['money'];

                $order->editOrder($value['orderid'], array('coupon' => $my_coupon, 'payment' => 'Western Union'));
            }

            $acctualTotal = ($total - $my_coupon);

            $total = round($total, 2);

            $my_coupon = round($my_coupon, 2);

            $acctualTotal = round($acctualTotal, 2);

            $this->view->assign('total', $total);

            $this->view->assign('my_coupon', $my_coupon);

            $this->view->assign('acctualTotal', $acctualTotal);

            $this->view->assign('item_name', $item_name);

            $this->view->assign('uid', $_COOKIE[COOKIE_PRE . 'uid']);

            $this->updateAccount($acctualTotal, 'Western Union');
        }
    }

    public function ttAction()
    {

        $my_coupon = $this->_request->getParam('my_coupon');

        $my_coupon = $my_coupon == '' ? 0 : $my_coupon;

        $member = new CMember();

        $memberArray = $member->getUserDetails(array('uid' => $_COOKIE[COOKIE_PRE . 'uid']));

        if ($memberArray[0]['my_coupon'] < $my_coupon)
        {

            $this->_helper->viewRenderer->setNoRender();

            $this->view->showMsg("Not enough coupons!");
        } else
        {

            $item_name = $this->_request->getParam('item_name');

            $order = new COrder();

            $total = 0;

            $orderArray = $order->getAllOrders(0, 0, $_COOKIE[COOKIE_PRE . 'uid'], "has_shutted='0' AND " . R_PRE . "orders.flid='1'");

            foreach ($orderArray as $value)
            {

                $total+=$value['money'];

                $order->editOrder($value['orderid'], array('coupon' => $my_coupon, 'payment' => 'tt'));
            }

            $acctualTotal = ($total - $my_coupon);

            $total = round($total, 2);

            $my_coupon = round($my_coupon, 2);

            $acctualTotal = round($acctualTotal, 2);

            $this->view->assign('total', $total);

            $this->view->assign('my_coupon', $my_coupon);

            $this->view->assign('acctualTotal', $acctualTotal);

            $this->view->assign('item_name', $item_name);

            $this->view->assign('uid', $_COOKIE[COOKIE_PRE . 'uid']);

            $this->updateAccount($acctualTotal, 'tt');
        }
    }
    
    public function yourspayreceiveAction()
    {
	    $MD5key = "pIesLirt";                       /** <非空>--密钥. 从网店系统中获取。**/
		$BillNo = $_POST["BillNo"];                 /** <非空>--订单号. 从yourspay服务器返回 **/
		$Currency = $_POST["Currency"];             /** <非空>--通道参数. 从yourspay服务器返回 **/
		$Amount = $_POST["Amount"];                 /** <非空>--金额. 从yourspay服务器返回**/
		$CurrencyCode = $_POST["CurrencyCode"];     /** <非空>--币种. 从yourspay服务器返回**/
		$Succeed = $_POST["Succeed"];               /** <非空>--支付状态.从yourspay服务器返回."0"表示支付失败，"1"表示支付成功,"2"表示待处理  **/
		$Result = $_POST["Result"];                 /** <非空>--支付结果. 从yourspay服务器返回**/
		$MD5info = $_POST["MD5info"];               /** <非空>--取得的MD5校验信息. 从yourspay服务器返回**/
		$Remark = $_POST["Remark"];                 /** <非空>--备注. 从yourspay服务器返回**/
		$md5src = $BillNo.$Currency.$Amount.$Succeed.$MD5key;    /** <非空>--参数组合.组合只能以这个顺序,位置不能颠倒 **/
		$md5sign = strtoupper(md5($md5src));        /** <非空>--对组合参数进行md5加密**/
		/** 对返回信息进行判断.然后把支付结果显示在返回页面中，并更新网店后台的订单状态. **/
    	$order = new COrder();
        $id = intval($_POST["BillNo"]);
        $orderArray = $order->getAllOrders(0, 0, 0, R_PRE . "orders.orderid = $id AND has_shutted='0' AND " . R_PRE . "orders.flid='1'");//orders.uid='" . $paramArray['uid'] . "' and 
        $uid = isset($orderArray[0]['uid']) ? $orderArray[0]['uid'] : 0;
        $orderidArray = array();
        
        $paid_total = 0;
		$payStatu = new CPaystatu();
        foreach ($orderArray as $value)
        {

            $orderidArray[] = $value['orderid'];
        }
		
		if($MD5info == $md5sign && $Succeed == "1")
		{
			/*
			 * 支付结果为:支付成功(Payment Result: Success)。
			 * 更新网店后台的订单状态为:支付成功(Success)。
			 */
			if(count($orderidArray)==0){
        		$this->_redirect('/adminb?iframeUrl=adminb-order-index');
        		return;
        	}
        	
            $allInfoArray = array();

            $paid_total = $this->getHelper('Order')->getTotal($orderidArray);
            $paid_total = $paid_total * CE_SSFKH;
            
            if (1 == 1)
            {           	
            	$this->updateIntegral($paid_total, $uid); //更新积分
            	$score = new CScore();
            	if ($score->orderScore('statu')) {
            		$scorePayStatu = 1;
            		$orderScoreStatu = 1;
            	} else {
            		$scorePayStatu = 0;
            		$orderScoreStatu = 0;
            	}
            	$member = new CMember();   
            	$useScore = $score->dollar2score($orderArray[0]['coupon']);    	
	            $member->updateIntegral($useScore, $uid);			    
                $order->editOrderArray($orderidArray, array('score_pay_statu'=>$scorePayStatu,'order_score_statu'=>$orderScoreStatu, 'flid' => 2, 'payment' => 'Credit Card', 'discount' => CE_SSFKH, 'pay_time' => time()));
            } else
            {
            }
			
            if (defined('SELL_VALIDATE')) {
            	$buyModel = new CPyramidMemberBuy();
            	$buyModel->edit(array('is_pay'=>1), $id);
            	$detailModel = new CPyramidAccountDetail();
            	if (defined('IS_SELF')) {
            		$self = 1;
            	} else {
            		$self = 0;
            	}
            	$detailModel->add(array('facebook_id'=>$_COOKIE[COOKIE_PRE.'inv_facebook_id'], 'from_facebook_id'=>$_COOKIE[COOKIE_PRE.'my_facebook_id'],
            							'amount'=>$paid_total / CE_SSFKH * SELL_BONUS, 'order_id'=>$id, 'is_self'=>$self, 'add_time'=>time()));
            	
            	$accountModel = new CPyramidMemberAccount();
            	//自己和好友的分成
            	//$accountModel->addAmount($paid_total / CE_SSFKH * SELL_BONUS, $_COOKIE[COOKIE_PRE.'my_facebook_id']);
            	$accountModel->addAmount($paid_total / CE_SSFKH * SELL_BONUS, $_COOKIE[COOKIE_PRE.'inv_facebook_id']);
            	
            	setcookie(COOKIE_PRE.'inv_facebook_id', $inv, time() - 1, '/');
				setcookie(COOKIE_PRE.'my_facebook_id', $currentUserId, time() - 1, '/');
				$invModel = new CPyramidMemberInv();
			
				$invModel->del($uid);
            }
            
            $account = new CAccount();

            $sign = $orderidArray[count($orderidArray) - 1];
            
            $accountArray = $account->getAccountDetails(array('sign' => $sign));

            if (count($accountArray) == 0)
            {
                /* 财务 */
                $accountData = array(
                    'should_paid' => $_POST["Amount"],
                    'has_paid' => $paid_total,
                    'flid' => 1,
                    'state' => 1,
                    'orderid_string' => serialize($orderidArray),
                    'from_uid' => $uid,
                    'to_uid' => 0,
                    'add_time' => time(),
                    'payment' => 'Credit Card',
                    'remark' => ''
                );

                $account->createAccount($accountData);
                /* 财务 */
            } else
            {
                $accountData = array(
                    'should_paid' => $_POST["Amount"],
                    'has_paid' => $paid_total,
                    'flid' => 1,
                    'state' => 1,
                    'orderid_string' => serialize($orderidArray),
                    'from_uid' => $uid,
                    'to_uid' => 0,
                    'add_time' => time(),
                    'payment' => 'Credit Card',
                    'remark' => ''
                );

                $account->editAccount($accountArray[0]['accountid'], $accountData);
            }

            $cart = new CCart();
	    	$db = $cart->getAdapter();
	    	$member = new CMember();
	    	if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer'){
	    		$where = $db->quoteInto('cart_session_id = ?', isset($_COOKIE[COOKIE_PRE . 'product_buy_session']) ? $_COOKIE[COOKIE_PRE . 'product_buy_session']: 0);    
	    		setcookie(COOKIE_PRE.'product_buy_session', '', time()-3600, '/');
	    	} else {
	    		$where = $db->quoteInto('uid = ?', $_COOKIE[COOKIE_PRE . 'uid']);
	    	}	
	    	$cart->delete($where);

	    	//发送邮件
            $config=new CConfigpayemail();
        	$array=$config->getAllConfigpayemail();
	        $configArray=array();
	        foreach ($array as $value) {
	            $configArray[$value['name']]=$value['data'];
	        }
        	
        	$orderContact=new COrderContact();
	        $buyerContactArray=$orderContact->getContactByid($orderArray[0]['contactid']);
	        $to = $buyerContactArray[0]['email'];
	        $subject = $configArray['EMAIL_TITLE'];
	        $message = str_replace("{#orderid}",$id, $configArray['EMAIL_BODY']);	
	
	        $message = str_replace("\r\n","<br>",$message);
	        $from = $configArray['EMAIL_BOX'];
	        $headers = "MIME-Version: 1.0" . "\r\n";
	        $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
	        $headers .= "From: $from";
	        mail($to,$subject,$message,$headers);
	        
	        //增加2个坑
	        $flashCommon = new CFlashcommon();
			$flashCommon->addItem($_COOKIE[COOKIE_PRE . 'uid'], 10);	  
			$flashItemLog = new CFlashitemorderlog();      
			$flashItemLog->insert(array('orderid'=>$id, 'buy_count'=>10, 'add_time'=>time()));
		}
		else if($MD5info == $md5sign && $Succeed == "2")
		{
			/*
			 * 支付结果为:支付待处理(Payment Result:Processing)。
			 * 更新网店后台的订单状态为:待处理(Processing)。
			 */
		}
		else if($MD5info == $md5sign && $Succeed == "0")
		{ 
			/*
			 * 支付结果为:支付失败(Payment Result: Fail)。
			 * 更新网店后台的订单状态为:支付失败(Fail)。
			 */
		}else{
			/*
			 * 支付结果为:数据校验失败(Payment Result: Data Authentication Failed)。
			 * 更新网店后台的订单状态为：支付失败(Fail)。
			 */
		}
    	$confirmation = new CConfirmation();
        $data = array(
            'uid' => $uid,
            'orderid_string' => serialize($orderidArray),
            'confirm_string' => serialize($allInfoArray),
            'add_time' => time(),
            'is_valid' => ($MD5info == $md5sign) ? 1 : 0,
            'total' => "0" . $_POST["Amount"],
            'paid_total' => $paid_total,
        );

		$confirmation->createConfirmation($data);
        //$mycoupon = new CCoupon();

        //$mycoupon->subCoupon($orderArray[0]['coupon'], "WHERE uid='" . $paramArray['uid'] . "'");
       
        $game = new CGame();
        $game->update(array('prize_order_id'=>$orderid, 'isprize'=>1), 'hashcode="' . $_COOKIE[COOKIE_PRE . 'prize_hash'].'"');
        //$this->updateIntegral($paid_total, $paramArray['uid']); //更新积分

		$this->view->md5sign = $md5sign;
		$this->view->MD5info = $MD5info;
		if ($MD5info == $md5sign){
        	$this->view->BillNo = $BillNo;
			$this->view->Currency = $Currency;
			$this->view->Amount = $Amount;
			$this->view->Succeed = $Succeed;
			$this->view->Result = $Result;
			$this->view->currencyName = $currencyName;
			$this->view->md5src = $md5src;
			$this->view->orderid = $id;
		}
		
		$payStatu->add(array('orderid'=>$BillNo, 'statu'=>$Result . ' yourspay by custom', 'add_time'=>date('Y-m-d H:i:s', time())));
    }

    public function updateAccount($total, $payment)
    {
    	

        $orderidArray = $this->_request->getParam('id');

        $account = new CAccount();

        $sign = $orderidArray[count($orderidArray) - 1];

        $accountArray = $account->getAccountDetails(array('sign' => $sign));

        if (count($accountArray) == 0)
        {

            try
            {

                $accountData = array(
                    'should_paid' => $total,
                    'has_paid' => 0,
                    'flid' => 1,
                    'state' => 0,
                    'orderid_string' => serialize($orderidArray),
                    'from_uid' => $_COOKIE[COOKIE_PRE . 'uid'],
                    'to_uid' => 0,
                    'discount' => 1,
                    'add_time' => time(),
                    'payment' => $payment,
                    'sign' => $sign,
                    'remark' => ''
                );

                $account->createAccount($accountData);
            } catch (Exception $e)
            {

            }
        } else
        {

            $accountData = array(
                'should_paid' => $total,
                'has_paid' => 0,
                'flid' => 1,
                'state' => 0,
                'orderid_string' => serialize($orderidArray),
                'from_uid' => $_COOKIE[COOKIE_PRE . 'uid'],
                'to_uid' => 0,
                'discount' => 1,
                'add_time' => time(),
                'payment' => $payment,
                'remark' => ''
            );

            $account->editAccount($accountArray[0]['accountid'], $accountData);
        }

        return true;
    }

    public function receiveAction()
    {

        $this->_helper->viewRenderer->setNoRender();

        $this->getHelper('layout')->disableLayout();

        $paid_total = 0;

        $paramArray = $this->_request->getParams();

        $paramArray['uid'] = $paramArray == '' ? 0 : $paramArray['uid'];

        $order = new COrder();

        $id = intval($this->getRequest()->getParam('id'));
        
        $orderArray = $order->getAllOrders(0, 0, 0, R_PRE . "orders.uid='" . $paramArray['uid'] . "' and orderid = $id AND has_shutted='0' AND " . R_PRE . "orders.flid='1'");

        $orderidArray = array();

        foreach ($orderArray as $value)
        {

            $orderidArray[] = $value['orderid'];
        }



        // read the post from PayPal system and add 'cmd'
        $req = 'cmd=_notify-validate';

        foreach ($_POST as $key => $value)
        {
            $value = urlencode(stripslashes($value));
            $req .= "&$key=$value";
        }

        // post back to PayPal system to validate
        $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";

        $fp = fsockopen('ssl://www.paypal.com', 443, $errno, $errstr, 30);

        $allInfoArray = array();

        if (!$fp)
        {
            // HTTP ERROR
        } else
        {
            fputs($fp, $header . $req);
            while (!feof($fp))
            {
                $res = fgets($fp, 1024);
                
                if (strcmp($res, "VERIFIED") == 0)
                {
                    // check the payment_status is Completed
                    // check that txn_id has not been previously processed
                    // check that receiver_email is your Primary PayPal email
                    // check that payment_amount/payment_currency are correct
                    // process payment
                    // echo the response
                    $allInfoArray['is_valid'] = $res;

                    //loop through the $_POST array and print all vars to the screen.

                    foreach ($_POST as $key => $value)
                    {

                        $allInfoArray['info'][$key] = $value;
                    }

                    $paid_total = $this->getHelper('Order')->getTotal($orderidArray);
					$paid_total = $paid_total * PAYPAL_RATE;
                    if ($allInfoArray['info']['mc_gross'] == $paid_total)
                    {
                    	$this->updateIntegral($paid_total, $paramArray['uid']); //更新积分
		            	$score = new CScore();
		            	if ($score->orderScore('statu')) {
		            		$scorePayStatu = 1;
		            		$orderScoreStatu = 1;
		            	} else {
		            		$scorePayStatu = 0;
		            		$orderScoreStatu = 0;
		            	}
                		$order->editOrderArray($orderidArray, array('score_pay_statu'=>$scorePayStatu,'order_score_statu'=>$orderScoreStatu, 'flid' => 2, 'payment' => 'paypal', 'discount' => PAYPAL_RATE, 'pay_time' => time()));

                       // $order->editOrderArray($orderidArray, array('flid' => 2, 'payment' => 'paypal', 'discount' => PAYPAL_RATE, 'pay_time' => time()));

                        // $member=new CMember();
                        //$member->updateIntegral($_COOKIE[COOKIE_PRE.'integral'],$_COOKIE[COOKIE_PRE.'uid'],1);
                        //$member->updateIntegral(2,$_COOKIE[COOKIE_PRE.'uid'],1);
                    } else
                    {

                        $allInfoArray['is_valid'] = 'INVALID';
                    }

                    $account = new CAccount();

                    $sign = $orderidArray[count($orderidArray) - 1];

                    $accountArray = $account->getAccountDetails(array('sign' => $sign));

                    if (count($accountArray) == 0)
                    {

                        /* 财务 */
                        $accountData = array(
                            'should_paid' => $allInfoArray['info']['mc_gross'],
                            'has_paid' => $paid_total,
                            'flid' => 1,
                            'state' => 1,
                            'orderid_string' => serialize($orderidArray),
                            'from_uid' => $paramArray['uid'],
                            'to_uid' => 0,
                            'add_time' => time(),
                            'payment' => 'paypal',
                            'remark' => ''
                        );

                        $account->createAccount($accountData);
                        /* 财务 */
                    } else
                    {

                        $accountData = array(
                            'should_paid' => $allInfoArray['info']['mc_gross'],
                            'has_paid' => $paid_total,
                            'flid' => 1,
                            'state' => 1,
                            'orderid_string' => serialize($orderidArray),
                            'from_uid' => $paramArray['uid'],
                            'to_uid' => 0,
                            'add_time' => time(),
                            'payment' => 'paypal',
                            'remark' => ''
                        );

                        $account->editAccount($accountArray[0]['accountid'], $accountData);
                    }
                } else if (strcmp($res, "INVALID") == 0)
                {
                    // log for manual investigation
                    // echo the response
                    $allInfoArray['is_valid'] = $res;
                }
            }
            fclose($fp);
        }



        $confirmation = new CConfirmation();

        $data = array(
            'uid' => $paramArray['uid'],
            'orderid_string' => serialize($orderidArray),
            'confirm_string' => serialize($allInfoArray),
            'add_time' => time(),
            'is_valid' => $allInfoArray['is_valid'] = strcmp($allInfoArray['is_valid'], "VERIFIED") == 0 ? 1 : 0,
            'total' => $allInfoArray['info']['mc_gross'],
            'paid_total' => $paid_total,
        );

        $confirmation->createConfirmation($data);
        
    }   
	
    /**富汇通**/
    public function ssfkhreceive1Action()
    {
        //$this->_helper->viewRenderer->setNoRender();
        //$this->getHelper('layout')->disableLayout();
  
        //返回结果
		//MD5私钥
		$MD5key = "123456";
    	
		
		$ReturnSucceed = 0;
		$payStatu = new CPaystatu();
		
		//订单号
		$BillNo = $_POST["BillNo"];
		//币种
		$Currency = $_POST["Currency"];
		//金额
		$Amount = $_POST["Amount"];
		//支付状态
		$Succeed = $_POST["Succeed"];
		//支付结果
		$Result = $_POST["Result"];
		//取得的MD5校验信息
		$MD5info = $_POST["MD5info"]; 
		//备注
		$Remark = $_POST["Remark"];
		//金额单位
		//$currencyName = $_POST["currencyName"];
		//校验源字符串
		$md5src = $BillNo.$Currency.$Amount.$Succeed.$MD5key;
  		//MD5检验结果
		$md5sign = strtoupper(md5($md5src));
		
		//$BankID = $_POST["BankID"];
		//$Drawee = $_POST["Drawee"];
		//$TradeNo = $_POST["TradeNo"];
        
        $paid_total = 0;

        $order = new COrder();
		
        $id = intval($_POST["BillNo"]);
        
        $orderArray = $order->getAllOrders(0, 0, 0, R_PRE . "orders.orderid = $id AND has_shutted='0' AND " . R_PRE . "orders.flid='1'");//orders.uid='" . $paramArray['uid'] . "' and 
  		
        $uid = isset($orderArray[0]['uid']) ? $orderArray[0]['uid'] : 0;
        
        $orderidArray = array();

        foreach ($orderArray as $value)
        {

            $orderidArray[] = $value['orderid'];
        }
        
        if ($Succeed=='1')
        {
            $allInfoArray = array();

            $paid_total = $this->getHelper('Order')->getTotal($orderidArray);
            $paid_total = $paid_total * CE_SSFKH;
            
            if (1 == 1)
            {           	
            	$this->updateIntegral($paid_total, $uid); //更新积分
            	$score = new CScore();
            	if ($score->orderScore('statu')) {
            		$scorePayStatu = 1;
            		$orderScoreStatu = 1;
            	} else {
            		$scorePayStatu = 0;
            		$orderScoreStatu = 0;
            	}
            	$member = new CMember();   
            	$useScore = $score->dollar2score($orderArray[0]['coupon']);    	
	            $member->updateIntegral($useScore, $uid);			    
                $order->editOrderArray($orderidArray, array('score_pay_statu'=>$scorePayStatu,'order_score_statu'=>$orderScoreStatu, 'flid' => 2, 'payment' => 'Credit Card', 'discount' => CE_SSFKH, 'pay_time' => time()));
            } else
            {
            }
			
            if (defined('SELL_VALIDATE')) {
            	$buyModel = new CPyramidMemberBuy();
            	$buyModel->edit(array('is_pay'=>1), $id);
            	$detailModel = new CPyramidAccountDetail();
            	if (defined('IS_SELF')) {
            		$self = 1;
            	} else {
            		$self = 0;
            	}
            	$detailModel->add(array('facebook_id'=>$_COOKIE[COOKIE_PRE.'inv_facebook_id'], 'from_facebook_id'=>$_COOKIE[COOKIE_PRE.'my_facebook_id'],
            							'amount'=>$paid_total / CE_SSFKH * SELL_BONUS, 'order_id'=>$id, 'is_self'=>$self, 'add_time'=>time()));
            	
            	$accountModel = new CPyramidMemberAccount();
            	//自己和好友的分成
            	//$accountModel->addAmount($paid_total / CE_SSFKH * SELL_BONUS, $_COOKIE[COOKIE_PRE.'my_facebook_id']);
            	$accountModel->addAmount($paid_total / CE_SSFKH * SELL_BONUS, $_COOKIE[COOKIE_PRE.'inv_facebook_id']);
            	
            	setcookie(COOKIE_PRE.'inv_facebook_id', $inv, time() - 1, '/');
				setcookie(COOKIE_PRE.'my_facebook_id', $currentUserId, time() - 1, '/');
				$invModel = new CPyramidMemberInv();
			
				$invModel->del($uid);
            }
            
            $account = new CAccount();

            $sign = $orderidArray[count($orderidArray) - 1];
            
            $accountArray = $account->getAccountDetails(array('sign' => $sign));

            if (count($accountArray) == 0)
            {
                // 财务 
                $accountData = array(
                    'should_paid' => $_POST["Amount"],
                    'has_paid' => $paid_total,
                    'flid' => 1,
                    'state' => 1,
                    'orderid_string' => serialize($orderidArray),
                    'from_uid' => $uid,
                    'to_uid' => 0,
                    'add_time' => time(),
                    'payment' => 'Credit Card',
                    'remark' => ''
                );

                $account->createAccount($accountData);
                // 财务 
            } else
            {
                $accountData = array(
                    'should_paid' => $_POST["Amount"],
                    'has_paid' => $paid_total,
                    'flid' => 1,
                    'state' => 1,
                    'orderid_string' => serialize($orderidArray),
                    'from_uid' => $uid,
                    'to_uid' => 0,
                    'add_time' => time(),
                    'payment' => 'Credit Card',
                    'remark' => ''
                );

                $account->editAccount($accountArray[0]['accountid'], $accountData);
            }

            $cart = new CCart();
	    	$db = $cart->getAdapter();
	    	$member = new CMember();
	    	if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer'){
	    		$where = $db->quoteInto('cart_session_id = ?', $_COOKIE[COOKIE_PRE . 'product_buy_session']);    
	    		setcookie(COOKIE_PRE.'product_buy_session', '', time()-3600, '/');
	    	} else {
	    		$where = $db->quoteInto('uid = ?', $_COOKIE[COOKIE_PRE . 'uid']);
	    	}	
	    	$cart->delete($where);

	    	//发送邮件
            $config=new CConfigpayemail();
        	$array=$config->getAllConfigpayemail();
	        $configArray=array();
	        foreach ($array as $value) {
	            $configArray[$value['name']]=$value['data'];
	        }
        	
        	$orderContact=new COrderContact();
	        $buyerContactArray=$orderContact->getContactByid($orderArray[0]['contactid']);
	        $to = $buyerContactArray[0]['email'];
	        $subject = $configArray['EMAIL_TITLE'];
	        $message = str_replace("{#orderid}",$id, $configArray['EMAIL_BODY']);	
	
	        $message = str_replace("\r\n","<br>",$message);
	        $from = $configArray['EMAIL_BOX'];
	        $headers = "MIME-Version: 1.0" . "\r\n";
	        $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
	        $headers .= "From: $from";
	        mail($to,$subject,$message,$headers);
	        
	        $flashCommon = new CFlashcommon();
			$flashCommon->addItem($uid, 10);
			$flashItemLog = new CFlashitemorderlog();      
			$flashItemLog->insert(array('orderid'=>$id, 'buy_count'=>10, 'add_time'=>time()));
			CStock::update($id); //更新库存
        } elseif ($Succeed == 0)
        {
        	$config=new CConfigpayemail();
        	$array=$config->getAllConfigpayemail();
	        $configArray=array();
	        foreach ($array as $value) {
	            $configArray[$value['name']]=$value['data'];
	        }
			$orderContact=new COrderContact();
	        $buyerContactArray=$orderContact->getContactByid($orderArray[0]['contactid']);
	        $to = $buyerContactArray[0]['email'];
	        $subject = str_replace("{#orderid}",$id, 'fancycheapjersey payment failure notice for order No.{#orderid}');
	        $message = "Dear $buyerContactArray[0]['name'],<br>
						We are sorry to inform that your payment for order #400 is failed due to following reason:<br>
						* payment declined by bank<br>
						You may use other credit card or other payment method to complete this payment. Sorry for the inconvenience caused. If there is any problem, please let us know throungh Facebook post. We will get back to you as soon as possible.<br> 
						Regards,<br>
						fancycheapjersey"	;	
	        $message = str_replace("\r\n","<br>",$message);
	        $from = $configArray['EMAIL_BOX'];
	        $headers = "MIME-Version: 1.0" . "\r\n";
	        $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
	        $headers .= "From: $from";
	        mail($to,$subject,$message,$headers);
        }

        $confirmation = new CConfirmation();
        $data = array(
            'uid' => $uid,
            'orderid_string' => serialize($orderidArray),
            'confirm_string' => serialize($allInfoArray),
            'add_time' => time(),
            'is_valid' => ($md5sign == $MD5info) ? 1 : 0,
            'total' => "0" . $_POST["Amount"],
            'paid_total' => $paid_total,
        );

		$confirmation->createConfirmation($data);
        //$mycoupon = new CCoupon();

        //$mycoupon->subCoupon($orderArray[0]['coupon'], "WHERE uid='" . $paramArray['uid'] . "'");
       
        $game = new CGame();
        $game->update(array('prize_order_id'=>$orderid, 'isprize'=>1), 'hashcode="' . $_COOKIE[COOKIE_PRE . 'prize_hash'].'"');
        //$this->updateIntegral($paid_total, $paramArray['uid']); //更新积分

		$this->view->md5sign = $md5sign;
		$this->view->MD5info = $MD5info;
		if ($MD5info == $md5sign){
        	$this->view->BillNo = $BillNo;
			$this->view->Currency = $Currency;
			$this->view->Amount = $Amount;
			$this->view->Succeed = $Succeed;
			$this->view->Result = $Result;
			//$this->view->currencyName = $currencyName;
			$this->view->md5src = $md5src;
			$this->view->orderid = $id;
		}
		
    	if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST') {
			//if ($Succeed=="1") {
				 $payStatu->add(array('orderid'=>$BillNo, 'statu'=>$Result . ' by custom', 'add_time'=>date('Y-m-d H:i:s', time())));
			//} elseif (empty($_POST["ReturnBillNo"])) {
				 //$payStatu->add(array('orderid'=>$BillNo, 'statu'=>$Result . ' by custom', 'add_time'=>date('Y-m-d H:i:s', time())));
			//}
		}
    }
    
	public function ssfkhreceiveAction()
    {
        //$this->_helper->viewRenderer->setNoRender();
        //$this->getHelper('layout')->disableLayout();
  
        //返回结果
		//MD5私钥
		$MD5key = "Zwj(u^qe";
		/**
		**判断是哪次返回的数据【顾客支付完立即返回，还是支付处理完以后返回的数据】
		*/
		$ReturnSucceed = 0;
		$payStatu = new CPaystatu();
		if(isset($_POST["ReturnBillNo"]) && !empty($_POST["ReturnBillNo"])){
			$this->getHelper('layout')->disableLayout();
			$this->getHelper('viewRenderer')->setNoRender();
			//订单号
			$returnBillNo = $_POST["ReturnBillNo"];	
			//币种
			$ReturnCurrency = $_POST["ReturnCurrency"];
			//金额
			$ReturnAmount = $_POST["ReturnAmount"];
			//支付状态
			$ReturnSucceed = $_POST["ReturnSucceed"];//返回码: 1 :表示交易成功 ; 0: 表示交易失败
			//支付结果
			$ReturnResult = $_POST["ReturnResult"];// success: 表示成功 ;fail:表示失败
			//取得的MD5校验信息
			$ReturnMD5info = $_POST["ReturnMD5info"]; 
			//校验源字符串
			$returnMd5src = $returnBillNo.$ReturnCurrency.$ReturnAmount.$ReturnSucceed.$MD5key;
		  //本地MD5检验结果
			$returnMd5sign = strtoupper(md5($returnMd5src));
			
			$payStatu->add(array('orderid'=>$returnBillNo, 'statu'=>$ReturnResult . ' by post', 'add_time'=>date('Y-m-d H:i:s', time())));
			
			if($returnMd5sign==$ReturnMD5info){
				if($ReturnSucceed=='1'){
					//支付已成功
					//请修改订单状态为成功状态
				}
				else if($ReturnSucceed=='0'){
					//支付已失败
					//请修改订单状态为失败状态
				}
			}
		} else {
		}
		//订单号
		$BillNo = $_POST["BillNo"];
		//币种
		$Currency = $_POST["Currency"];
		//金额
		$Amount = $_POST["Amount"];
		//支付状态
		$Succeed = $_POST["Succeed"];
		//支付结果
		$Result = $_POST["Result"];
		//取得的MD5校验信息
		$MD5info = $_POST["MD5info"]; 
		//备注
		//$Remark = $_POST["Remark"];
		//金额单位
		$currencyName = $_POST["currencyName"];
		//校验源字符串
		$md5src = $BillNo.$Currency.$Amount.$Succeed.$MD5key;
  		//MD5检验结果
		$md5sign = strtoupper(md5($md5src));
        
        $paid_total = 0;

        $order = new COrder();
		
        $id = intval($_POST["BillNo"]);
        
        $orderArray = $order->getAllOrders(0, 0, 0, R_PRE . "orders.orderid = $id AND has_shutted='0' AND " . R_PRE . "orders.flid='1'");//orders.uid='" . $paramArray['uid'] . "' and 
  		
        $uid = isset($orderArray[0]['uid']) ? $orderArray[0]['uid'] : 0;
        
        $orderidArray = array();

        foreach ($orderArray as $value)
        {

            $orderidArray[] = $value['orderid'];
        }
        
        if ($ReturnSucceed=='1' || $Succeed=='88')
        {
        	
        	if(count($orderidArray)==0){
        		$this->_redirect('/adminb?iframeUrl=adminb-order-index');
        		return;
        	}
        	
            $allInfoArray = array();

            $paid_total = $this->getHelper('Order')->getTotal($orderidArray);
            $paid_total = $paid_total * CE_SSFKH;
            
            if (1 == 1)
            {           	
            	$this->updateIntegral($paid_total, $uid); //更新积分
            	$score = new CScore();
            	if ($score->orderScore('statu')) {
            		$scorePayStatu = 1;
            		$orderScoreStatu = 1;
            	} else {
            		$scorePayStatu = 0;
            		$orderScoreStatu = 0;
            	}
            	$member = new CMember();   
            	$useScore = $score->dollar2score($orderArray[0]['coupon']);    	
	            $member->updateIntegral($useScore, $uid);			    
                $order->editOrderArray($orderidArray, array('score_pay_statu'=>$scorePayStatu,'order_score_statu'=>$orderScoreStatu, 'flid' => 2, 'payment' => 'Credit Card', 'discount' => CE_SSFKH, 'pay_time' => time()));
            } else
            {
            }
			
            if (defined('SELL_VALIDATE')) {
            	$buyModel = new CPyramidMemberBuy();
            	$buyModel->edit(array('is_pay'=>1), $id);
            	$detailModel = new CPyramidAccountDetail();
            	if (defined('IS_SELF')) {
            		$self = 1;
            	} else {
            		$self = 0;
            	}
            	$detailModel->add(array('facebook_id'=>$_COOKIE[COOKIE_PRE.'inv_facebook_id'], 'from_facebook_id'=>$_COOKIE[COOKIE_PRE.'my_facebook_id'],
            							'amount'=>$paid_total / CE_SSFKH * SELL_BONUS, 'order_id'=>$id, 'is_self'=>$self, 'add_time'=>time()));
            	
            	$accountModel = new CPyramidMemberAccount();
            	//自己和好友的分成
            	//$accountModel->addAmount($paid_total / CE_SSFKH * SELL_BONUS, $_COOKIE[COOKIE_PRE.'my_facebook_id']);
            	$accountModel->addAmount($paid_total / CE_SSFKH * SELL_BONUS, $_COOKIE[COOKIE_PRE.'inv_facebook_id']);
            	
            	setcookie(COOKIE_PRE.'inv_facebook_id', $inv, time() - 1, '/');
				setcookie(COOKIE_PRE.'my_facebook_id', $currentUserId, time() - 1, '/');
				$invModel = new CPyramidMemberInv();
			
				$invModel->del($uid);
            }
            
            $account = new CAccount();

            $sign = $orderidArray[count($orderidArray) - 1];
            
            $accountArray = $account->getAccountDetails(array('sign' => $sign));

            if (count($accountArray) == 0)
            {
                /* 财务 */
                $accountData = array(
                    'should_paid' => $_POST["Amount"],
                    'has_paid' => $paid_total,
                    'flid' => 1,
                    'state' => 1,
                    'orderid_string' => serialize($orderidArray),
                    'from_uid' => $uid,
                    'to_uid' => 0,
                    'add_time' => time(),
                    'payment' => 'Credit Card',
                    'remark' => ''
                );

                $account->createAccount($accountData);
                /* 财务 */
            } else
            {
                $accountData = array(
                    'should_paid' => $_POST["Amount"],
                    'has_paid' => $paid_total,
                    'flid' => 1,
                    'state' => 1,
                    'orderid_string' => serialize($orderidArray),
                    'from_uid' => $uid,
                    'to_uid' => 0,
                    'add_time' => time(),
                    'payment' => 'Credit Card',
                    'remark' => ''
                );

                $account->editAccount($accountArray[0]['accountid'], $accountData);
            }

            $cart = new CCart();
	    	$db = $cart->getAdapter();
	    	$member = new CMember();
	    	if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer'){
	    		$where = $db->quoteInto('cart_session_id = ?', isset($_COOKIE[COOKIE_PRE . 'product_buy_session']) ? $_COOKIE[COOKIE_PRE . 'product_buy_session']: 0);    
	    		setcookie(COOKIE_PRE.'product_buy_session', '', time()-3600, '/');
	    	} else {
	    		$where = $db->quoteInto('uid = ?', $_COOKIE[COOKIE_PRE . 'uid']);
	    	}	
	    	$cart->delete($where);

	    	//发送邮件
            $config=new CConfigpayemail();
        	$array=$config->getAllConfigpayemail();
	        $configArray=array();
	        foreach ($array as $value) {
	            $configArray[$value['name']]=$value['data'];
	        }
        	
        	$orderContact=new COrderContact();
	        $buyerContactArray=$orderContact->getContactByid($orderArray[0]['contactid']);
	        $to = $buyerContactArray[0]['email'];
	        $subject = $configArray['EMAIL_TITLE'];
	        $message = str_replace("{#orderid}",$id, $configArray['EMAIL_BODY']);	
	
	        $message = str_replace("\r\n","<br>",$message);
	        $from = $configArray['EMAIL_BOX'];
	        $headers = "MIME-Version: 1.0" . "\r\n";
	        $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
	        $headers .= "From: $from";
	        mail($to,$subject,$message,$headers);
	        
	        //增加2个坑
	        $flashCommon = new CFlashcommon();
			$flashCommon->addItem($_COOKIE[COOKIE_PRE . 'uid'], 10);	  
			$flashItemLog = new CFlashitemorderlog();      
			$flashItemLog->insert(array('orderid'=>$id, 'buy_count'=>10, 'add_time'=>time()));
        } else
        {

        }

        $confirmation = new CConfirmation();
        $data = array(
            'uid' => $uid,
            'orderid_string' => serialize($orderidArray),
            'confirm_string' => serialize($allInfoArray),
            'add_time' => time(),
            'is_valid' => ($MD5info == $md5sign) ? 1 : 0,
            'total' => "0" . $_POST["Amount"],
            'paid_total' => $paid_total,
        );

		$confirmation->createConfirmation($data);
        //$mycoupon = new CCoupon();

        //$mycoupon->subCoupon($orderArray[0]['coupon'], "WHERE uid='" . $paramArray['uid'] . "'");
       
        $game = new CGame();
        $game->update(array('prize_order_id'=>$orderid, 'isprize'=>1), 'hashcode="' . $_COOKIE[COOKIE_PRE . 'prize_hash'].'"');
        //$this->updateIntegral($paid_total, $paramArray['uid']); //更新积分

		$this->view->md5sign = $md5sign;
		$this->view->MD5info = $MD5info;
		if ($MD5info == $md5sign){
        	$this->view->BillNo = $BillNo;
			$this->view->Currency = $Currency;
			$this->view->Amount = $Amount;
			$this->view->Succeed = $Succeed;
			$this->view->Result = $Result;
			$this->view->currencyName = $currencyName;
			$this->view->md5src = $md5src;
			$this->view->orderid = $id;
		}
		
		if ($Succeed=="1" || $Succeed=="9" || $Succeed=="19" || $Succeed=="88") {
			 $payStatu->add(array('orderid'=>$BillNo, 'statu'=>$Result . ' by custom', 'add_time'=>date('Y-m-d H:i:s', time())));
		} elseif (empty($_POST["ReturnBillNo"])) {
			 $payStatu->add(array('orderid'=>$BillNo, 'statu'=>$Result . ' by custom', 'add_time'=>date('Y-m-d H:i:s', time())));
		} else {
			 $payStatu->add(array('orderid'=>$BillNo, 'statu'=>$Result . ' by custom', 'add_time'=>date('Y-m-d H:i:s', time())));
		}
    }
    
    protected function updateIntegral($dollar, $uid)
    {
    	
    	$score = new CScore();
    	if ($score->orderScore('statu') == 1) {
	    	$score->updateIntegralByDollar($dollar, $uid);
	    	$fenlei = new CFenlei('product');
	    	$fenlei->refreshIntegral();
    	}
    }
    
	public function creditAction()
    {
        $paid_total = 0;

        $order = new COrder();
		
        $id = intval($_GET['id']);
        
        $orderArray = $order->getAllOrders(0, 0, 0, R_PRE . "orders.orderid = $id AND has_shutted='0' AND " . R_PRE . "orders.flid='1'");//orders.uid='" . $paramArray['uid'] . "' and 
  		if (empty($orderArray)) {
  			exit();
  		}
        $uid = isset($orderArray[0]['uid']) ? $orderArray[0]['uid'] : 0;
        
        $orderidArray = array();

        foreach ($orderArray as $value)
        {

            $orderidArray[] = $value['orderid'];
        }
        
		$paid_total = $this->getHelper('Order')->getTotal($orderidArray);
        
        $flashCommon = new CFlashcommon();
        
        $creditAmount = $flashCommon->getAvaiAmount($uid);
        
        if ($paid_total / 5 > $creditAmount) {
        	$this->view->Succeed = 0;
        	$this->view->result = 'no enough credit';
        	$this->view->BillNo = $id;
        	$this->view->Amount = round($paid_total/5,2);
        	return;
        }
        $db = $order->getAdapter();      
		$sql = 'update zcshop_mlm_member set cash=cash-' . round($paid_total/5, 2). ', update_time=' . time() . ' where uid = ' . intval($uid);   
            if ($db->query($sql))
            {           	
            	$this->updateIntegral($paid_total, $uid); //更新积分
            	$score = new CScore();
            	if ($score->orderScore('statu')) {
            		$scorePayStatu = 1;
            		$orderScoreStatu = 1;
            	} else {
            		$scorePayStatu = 0;
            		$orderScoreStatu = 0;
            	}
            	$member = new CMember();   
            	$useScore = $score->dollar2score($orderArray[0]['coupon']);    	
	            $member->updateIntegral($useScore, $uid);			    
                $order->editOrderArray($orderidArray, array('score_pay_statu'=>$scorePayStatu,'order_score_statu'=>$orderScoreStatu, 'flid' => 2, 'payment' => 'Credits', 'discount' => CE_SSFKH, 'pay_time' => time()));
            
			
	           
	
		    	//发送邮件
	            $config=new CConfigpayemail();
	        	$array=$config->getAllConfigpayemail();
		        $configArray=array();
		        foreach ($array as $value) {
		            $configArray[$value['name']]=$value['data'];
		        }
	        	
	        	$orderContact=new COrderContact();
		        $buyerContactArray=$orderContact->getContactByid($orderArray[0]['contactid']);
		        $to = $buyerContactArray[0]['email'];
		        $subject = $configArray['EMAIL_TITLE'];
		        $message = str_replace("{#orderid}",$id, $configArray['EMAIL_BODY']);	
		
		        $message = str_replace("\r\n","<br>",$message);
		        $from = $configArray['EMAIL_BOX'];
		        $headers = "MIME-Version: 1.0" . "\r\n";
		        $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
		        $headers .= "From: $from";
		        mail($to,$subject,$message,$headers);
		        
		        //增加2个坑
		        $flashCommon = new CFlashcommon();
				$flashCommon->addItem($_COOKIE[COOKIE_PRE . 'uid'], 10);	  
				$flashItemLog = new CFlashitemorderlog();      
				$flashItemLog->insert(array('orderid'=>$id, 'buy_count'=>10, 'add_time'=>time()));
				$Result = 'Success';
				$this->view->Succeed = 88;	        	
	        	$this->view->BillNo = $id;
            } else
            {
            	$Result = 'failure';
            	$this->view->Succeed = 88;	        	
	        	$this->view->BillNo = $id;
            }
            $this->view->Amount = round($paid_total/5,2);
            $payStatu = new CPaystatu();
			$payStatu->add(array('orderid'=>$id, 'statu'=>$Result . ' by custom', 'add_time'=>date('Y-m-d H:i:s', time())));		
    }

    public function postAction()
    {
        //$this->_helper->viewRenderer->setNoRender();
        //$this->getHelper ('layout')->disableLayout ();
    }
    
    public function westcnAction()
    {
    	$this->_helper->viewRenderer->setNoRender();
        $this->getHelper ('layout')->disableLayout ();
        $id = $this->getRequest()->getParam('id', 0);
        $mtcn = $this->getRequest()->getParam('mtcn', 0);
        $sendname = $this->getRequest()->getParam('sendname', 0);
        if ($id) {
       		$westInfo = new CWestinfo();
       		$westInfo->updateInfo($id, $mtcn, $sendname);
       		CStock::update($id); //更新库存
       		exit('1');
        } else {
        	exit('0');
        }
    }

}
